package com.heima.user.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;

import java.util.Map;

public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    @Override
    public ResponseResult<Map<String, Object>> login(LoginDto dto) {
        //1.先校验是否是空数据
        if (ObjectUtil.hasEmpty(dto.getPhone(), dto.getPassword())) {
            return ResponseResult.okResult(MapUtil.<String, Object>builder().put("token", AppJwtUtil.getToken(0L)).build());
        }
        //2.进入数据库查询数据
        ApUser apUser = this.getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));

        //判断数据
        if (ObjectUtil.isEmpty(apUser)) {
            //说明不存在用户
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST, "手机号未注册");
        }
        //3.判断密码
        if (ObjectUtil.notEqual(apUser.getPassword(), DigestUtil.md5(dto.getPassword()))) {
            //说明密码错误
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //将数据进行删除
        apUser.setSalt(null);
        apUser.setPassword(null);
        //正常登录
        return ResponseResult.okResult(MapUtil.<String, Object>builder()
                .put("token", AppJwtUtil.getToken(Convert.toLong(apUser.getId())))
                .put("user", apUser)
                .build());
    }
}
